package com.ygxsk.carhome.ui.message;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.response.MessageListItemBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.MessageListItemAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-08-03  18:14
 * @Description:消息列表的内容
 */
public class MessageListActivity extends ErrorActivity {

    //消息列表暂时无筛选能力
    @BindView(R.id.refreshlayoutinmessagelist)
    SmartRefreshLayout refreshLayoutInMessageList;

    @BindView(R.id.recyclerviewinmessagelist)
    RecyclerView recyclerViewInMessageList;

    private ArrayList<MessageListItemBean> mDataResources = new ArrayList<>();

    private MessageListItemAdapter messageListItemAdapter;
    //上传最后一条通知的id;
    private String notificationId_upLoad;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        initloading();

        initViews();

        gainDatas();

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_message_list;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_message));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);

                methodBack();

            }
        });

        //添加潜在客户的按钮
        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(false, 0, "添加", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//                //快速双加的限制，
//                // : 2023-07-11 16:18 提交潜在客户的信息
//                Bundle extra_bundle = new Bundle();
//                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //布局的适配器填充，下拉刷新等等；
        recyclerViewInMessageList.setLayoutManager(new MyLinearLayoutManager(this));
        messageListItemAdapter = new MessageListItemAdapter(R.layout.messageadapter, mDataResources);
        recyclerViewInMessageList.setAdapter(messageListItemAdapter);
        messageListItemAdapter.notifyDataSetChanged();

        // TODO: 2023-08-21 20:02 是一个子类的点击查看,如果将来放开再添加
//        messageListItemAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//
//                switch (view.getId()) {
//
//                    case R.id.textviewlookdetail: {
//
//                        //直接查看消息详情列表
//
//                        break;
//                    }
//
//                    default:
//                        break;
//                }
//            }
//        });


        refreshLayoutInMessageList.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        if (messageListItemAdapter != null) {
                            messageListItemAdapter.notifyDataSetChanged();
                        }

                        //重置内容
                        notificationId_upLoad = "";

                        getServerDatas(notificationId_upLoad);

                        refreshLayout.finishRefresh();
                    }
                });
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        //重新添加判断内容
                        if (NetworkUtils.isConnected()) {

                            getServerDatas(notificationId_upLoad);

                        } else {
                            netWorkError();
                        }

                        refreshLayout.finishLoadMore();

                    }
                });

            }
        });

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            if (mDataResources != null && mDataResources.isEmpty()) {
                mDataResources.clear();
            }

            notificationId_upLoad = "";

            getServerDatas(notificationId_upLoad);

        } else {
            netWorkError();
            setEnableLoadmore(refreshLayoutInMessageList, false);
        }

    }

    private void getServerDatas(String _notificationId_upLoad) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.notificationId, _notificationId_upLoad);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETMESSAGE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getTenementNotificationPageUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志 因为有加载更多无数据的时候告知用户--不告知也行，因为是首界面
        addLogUpLoadInfo.setHashMapParameter(map);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)//
                .getTenementNotificationPage(RequestBody.create(JSON.toJSONString(map, //
                                SerializerFeature.PrettyFormat,//
                                SerializerFeature.WriteMapNullValue), //
                        MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(MessageListActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<MessageListItemBean>>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        //如果获取消息列表本身出错，
                        //methodHandlerOtherForItSelf();
                    }

                    @Override
                    public void onErrorServerNotSuccessDataResponse(int method, boolean isToastToUser, Activity _activity, String statusCode, String message) {
                        super.onErrorServerNotSuccessDataResponse(method, isToastToUser, _activity, statusCode, message);

//                        LogUtils.d(ConstantApi.LOGCAT_NOMAL + "消息列表的 onErrorServerNotSuccessDataResponse 线程-->" + Thread.currentThread());
                        //main, com.dgj.propertysmart.ui.home.MessageFragment$8.onErrorServerNotSuccessDataResponse(MessageFragment.java:480)
                        //itchen->消息列表的 onErrorServerNotSuccessDataResponse 线程-->Thread[main,5,main]

                        //这里不需要区分是哪个接口，是它自己专属的处理方式
                        if (mDataResources != null && mDataResources.isEmpty()) {

                            //去掉上拉加载更多
                            setEnableLoadmore(refreshLayoutInMessageList, false);

                            CommUtils.checkCurrently(MessageListActivity.this,//
                                    statusCode,//
                                    R.drawable.errorsear,//
                                    message,//第一选择
                                    StringUtils.getString(R.string.nulldatanow));//

                        } else {
                            //那就是仅仅是提示 super.onErrorServerResponse(method, statusCode, message);已经处理了提示
                        }

                    }

                    @Override
                    public void onExceptionRequest(int method, Activity _activity, Exception exception) {
                        super.onExceptionRequest(method, _activity, exception);
                        setEnableLoadmore(refreshLayoutInMessageList, false);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "消息列表的doOnSubscribe 线程-->" + Thread.currentThread());
                        //itchen-->消息列表的doOnSubscribe 线程-->Thread[main,5,main]
                        loadingGone();
                        setEnableLoadmore(refreshLayoutInMessageList, true);
                    }
                }).subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<ArrayList<MessageListItemBean>>() {
                    @Override
                    public void accept(ArrayList<MessageListItemBean> messageListItemBeans) throws Throwable {

                        if (messageListItemBeans != null && !messageListItemBeans.isEmpty()) {

                            if (mDataResources != null) {

                                mDataResources.addAll(messageListItemBeans);

                                notificationId_upLoad = mDataResources.get(mDataResources.size() - 1).getNotificationId();

                                //LogUtils.d(ConstantApi.LOGCAT_NOMAL, "执行--methodHandlerOtherForI tSelf");
                            }

                            //非20000的界面处理
                            //是不是空数据,非20000，都要刷新该界面--
                            //仅仅只有一步 操作 可以不用rx改造 2020-6-17 14:39:09
                            if (messageListItemAdapter != null) {
                                messageListItemAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException apiException) {
                        //页面报错
                        if (apiException != null) {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + apiException.getDisplayMessage());
                        }
                    }
                });

    }


    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (messageListItemAdapter != null) {
            messageListItemAdapter.notifyDataSetChanged();
            messageListItemAdapter = null;
        }

    }
}